#! /usr/bin/env python
# -*- coding: utf-8 -*-

# @author: xmj
# @date: 2023/5/2

import os
import time
import threading
from common.get_path import *
from common.init_logging import *
from parse_config.parse_config import ParseConfig
from common.send_request import SendRequest
from common.create_report import create_html_report
from common.utils import *


total = 0
success = 0
res = []
is_auth = ParseConfig(config_path).parse_conf()['auth']['need']
code = ParseConfig(config_path).parse_conf()['auth']['code']
cup_auth = ParseConfig(config_path).parse_conf()['auth']['cup-auth']
urls = ParseConfig(config_path).parse_url()
endpoints = ParseConfig(config_path).parse_endpoint()


class CreateThread(threading.Thread):

    def __init__(self, lock, urls, is_auth, cup_auth, code):
        super().__init__()
        self.lock = lock
        self.urls = urls
        self.is_auth = is_auth
        self.cup_auth = cup_auth
        self.code = code

    def run(self):
        result, total_num, success_num = SendRequest(self.urls, self.is_auth, self.cup_auth, self.code).send_get_request()
        global total
        global success
        global res
        self.lock.acquire()
        res += result
        total += total_num
        success += success_num
        self.lock.release()


def start_scan(urls, endpoints):
    """
    main函数
    :param urls: 请求接口的url列表
    :param endpoints: 请求接口列表
    :return:
    """
    # 先按照url的个数来启动线程的个数
    for i in range(len(urls)):
        lock = threading.Lock()
        t = CreateThread(lock, [urls[i] + x for x in endpoints], is_auth, cup_auth, code)
        t.start()


def print_summary(total_num, success_num, start_time):
    """
    命令行打印汇总信息
    :param total_num:
    :param success_num:
    :param start_time:
    :return:
    """
    print("************************Scan Result************************")
    print("    Total sent: " + str(total_num))
    print("    Success: " + str(success_num))
    print("    Failed: " + str(total_num - success_num))
    print("")
    print("    Details in report_scan_" + start_time + ".html")
    print("***********************************************************")


if __name__ == "__main__":

    start_time = get_str_time()
    init_logging(start_time[0])
    start_scan(urls, endpoints)
    while 1:
        # 循环等待各个线程结束
        if len(threading.enumerate()) == 1:
            end_time = get_str_time()
            create_html_report(
                total_num=total,
                success_num=success,
                fail_num=total - success,
                start_time=start_time[1],
                end_time=end_time[1],
                report_time=end_time[0],
                interval=get_time_interval(start_time[0], end_time[0]),
                is_auth=('是' if is_auth == 1 else '否'),
                # 从所有结果里面筛选出失败的作为一个列表
                fail_list=[x for x in res if x['result'] == 'Fail'],
                # 从所有结果里面筛选出成功的作为一个列表
                pass_list=[x for x in res if x['result'] == 'Pass']
            )
            print_summary(total, success, end_time[0])
            break
        else:
            time.sleep(0.5)
    os.system('pause')
